package com.cysion.study.ui

import android.text.TextUtils
import android.view.View
import android.widget.CompoundButton
import com.cysion.study.ktbox.base.BaseActivity
import com.cysion.study.ktbox.net.BaseResponseRx
import com.cysion.study.ktbox.net.ErrorHandler
import com.cysion.study.ktbox.utils.whiteTextTheme
import com.cysion.other.color
import com.cysion.targetfun._subscribe
import com.cysion.study.uibox.bar.TopBar
import com.cysion.study.uibox.dialog.Alert
import com.cysion.study.R
import com.cysion.study.entity.ManagesEntity
import com.cysion.study.helper.UserCache
import com.cysion.study.net.ApiClient
import com.cysion.study.widget.ShowToast
import com.cysion.study.widget.downmenu.MenuItem
import com.cysion.study.widget.downmenu.SimpleDropDownMenu
import kotlinx.android.synthetic.main.activity_prview_edit.*

class PrviewEditActivity : BaseActivity(), View.OnClickListener, SimpleDropDownMenu.OnDropDownMenuOpenStateListener,
    SimpleDropDownMenu.OnMenuItemClickListener, CompoundButton.OnCheckedChangeListener {


    override fun getLayoutId(): Int = R.layout.activity_prview_edit
    var type: String = ""


    override fun initView() {
        type = intent.getBundleExtra("key").getString("type")

        whiteTextTheme(color(R.color.main_cl))
        topbar.apply {
            if (type == "1") {
                setTitle("增加家教信息")
            } else {
                setTitle("编辑家教信息")
            }
            setOnTopBarClickListener { obj, pos ->
                if (pos == TopBar.Pos.LEFT) {
                    finish()
                }
            }
        }
        //type 1新增 2编辑
        if (type == "2") {
            obj = intent.getBundleExtra("key").getSerializable("obj") as ManagesEntity?
            inView()
        } else {

            sm_ke.addMenuItemForTitle(mKeList, kecheng)
            sm_2.addMenuItemForTitle(mItemList, ms)

        }

        cb_age.setOnCheckedChangeListener(this)
        cb_xue.setOnCheckedChangeListener(this)

        tv_submit.setOnClickListener(this)
        sm_ke.showImgIcon(false)
        sm_2.showImgIcon(false)
        sm_xue.showImgIcon(false)
        sm_ke.dropDownMenuOpenStateListener = this

        sm_ke.menuItemClickListener = this
        sm_xue.menuItemClickListener = this
        sm_2.menuItemClickListener = this
        sm_xue.setOnClickListener(this)
        sm_ke.setOnClickListener(this)
        sm_2.setOnClickListener(this)

        //获取课程，及课程分类
        // /education/teacher/category/getList  我用的这个不传father  就是第一个  传father是第二个  page传1   limt传10000
        ///education/teacher/level/getLevel  获取学阶
        getCategoryList("")

        getLevel()
    }

    private fun getCategoryList(father: String) {
        Alert.loading(self)
        ApiClient.api.getCategoryList(UserCache.token, father, "1", "10000").compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    if (TextUtils.isEmpty(father)) {
                        for (level in it) {
                            mKeList.add(MenuItem(level.father, level.name, level.level))
                        }
                        //type 1新增 2编辑
                        if (type == "1") {
                            sm_ke.addMenuItemForTitle(mKeList, kecheng)
                        }
                    } else {
                        for (level in it) {
                            mItemList.add(MenuItem(level.father, level.name, level.level))
                        }
                        sm_2.addMenuItemForTitle(mItemList, ms)
                        sm_2.openMenu()
                    }

                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }

    }

    var kecheng: MenuItem = MenuItem(0, "选择课程", "")
    var ms: MenuItem = MenuItem(0, "选择课程分类", "")
    private var mx: MenuItem = MenuItem(0, "选择学阶", "")

    private var xueItemList = mutableListOf<MenuItem>()

    private var mKeList = mutableListOf<MenuItem>()
    private var mItemList = mutableListOf<MenuItem>()
    private fun getLevel() {
        Alert.loading(self)
        ApiClient.api.getLevel(UserCache.token).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    for (level in it) {
                        xueItemList.add(MenuItem(0, level.name, level.level))
                    }
                    sm_xue.addMenuItemForTitle(xueItemList, mx)

                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }


    override fun dropDownMenuStateChanges(menuOpenState: Boolean) {}
    //下拉点击回调
    override fun onMenuItemClickListener(v: View, position: Int) {
        if (selectType == "0") {
//            ShowToast("点击第 $position 项" + xueItemList.get(position).itemTitle)
            sm_xue.setTitleItem(MenuItem(0, xueItemList.get(position).itemTitle, xueItemList.get(position).itemId))
            level = xueItemList.get(position).itemId
        } else if (selectType == "1") {
            sm_ke.setTitleItem(MenuItem(0, mKeList.get(position).itemTitle, mKeList.get(position).itemId))
            oneCategory = mKeList.get(position).itemId
            father = mKeList.get(position).itemIcon.toString()
        } else if (selectType == "2") {
            sm_2.setTitleItem(MenuItem(0, mItemList.get(position).itemTitle, mItemList.get(position).itemId))
            twoCategory = mItemList.get(position).itemId
        }

    }

    var selectType = ""
    var oneCategory = ""//课程一级
    var father = ""//课程一级
    var twoCategory = ""//课程二级
    var level = ""//学阶等级

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_submit -> {
                submit()
            }
            R.id.sm_xue -> {
                selectType = "0"
                sm_xue.openMenu()
            }
            R.id.sm_ke -> {
                selectType = "1"//下拉菜单里判断点击回调哪个下拉菜单
                sm_ke.openMenu()
                father = ""//请求课程分类的父id  重新选择父菜单时 置空它
                oneCategory = ""
                twoCategory = ""
                sm_2.setTitleItem(ms)
            }
            R.id.sm_2 -> {
                if (TextUtils.isEmpty(oneCategory) && TextUtils.isEmpty(father)) {
                    ShowToast("请选择课程")
                    return
                }
                selectType = "2"
                getCategoryList(father)

            }
        }

    }

    private fun submit() {
        var money = et_name.text.toString().trim()
        var units = et_unit.text.toString().trim()
        var area = et_area.text.toString().trim()
        var age = et_age.text.toString().trim()
        var content = et_jj.text.toString().trim()
        var resg = et_phone.text.toString().trim()//资格证
        et_name.checkBlank("价格不能为空") ?: return
        et_unit.checkBlank("单位不能为空") ?: return
        et_area.checkBlank("区域不能为空") ?: return
        if (TextUtils.isEmpty(oneCategory)) {
            ShowToast("请选择课程")
            return
        }
        if (TextUtils.isEmpty(twoCategory)) {
            ShowToast("请选择课程分类")
            return
        }

        //家教类型 0.年龄段 1.学阶
        var type = ""
        if (cb_age.isChecked) {
            et_age.checkBlank("年龄不能为空") ?: return
            type = "0"
        }
        if (cb_xue.isChecked) {
            if (TextUtils.isEmpty(level)) {
                ShowToast("请选择学阶")
                return
            }
            type = "1"
        }
        et_jj.checkBlank("授课内容不能为空") ?: return
        et_phone.checkBlank("资格证不能为空") ?: return
        Alert.loading(self)
        ApiClient.api.addTeacher(
            UserCache.token,
            money,
            units,
            type,
            age,
            level,
            content,
            resg,
            oneCategory,
            twoCategory
        ).compose(BaseResponseRx.validateToMain())
            ._subscribe {
                _onNext {
                    Alert.close()
                    ShowToast("添加成功")
                    finish()
                }
                _onError {
                    Alert.close()
                    ShowToast(ErrorHandler.handle(it).errorMsg)
                }
            }
    }


    var obj: ManagesEntity? = null

    private fun inView() {
        et_name.setText(obj?.money)
        et_unit.setText(obj?.units)
        et_area.setText(obj?.province + obj?.city + obj?.county)
//        tv_kc.setText(obj?.oneCategoryName)
//        tv_kclb.setText(obj?.twoCategoryName)
        sm_ke.setTitleItem(MenuItem(0, obj?.oneCategoryName.toString(), obj?.oneCategory.toString()))
        sm_2.setTitleItem(MenuItem(0, obj?.twoCategoryName.toString(), obj?.twoCategory.toString()))
        oneCategory= obj?.oneCategory.toString()

        //家教类型 0.年龄段 1.学阶
        if (obj?.type == "1") {
            cb_xue.isChecked = true
            cb_age.isChecked = false
            sm_xue.setTitleItem(MenuItem(0, obj?.levelName.toString(), obj?.level.toString()))
            level=obj?.level.toString()
        } else {
            cb_xue.isChecked = false
            cb_age.isChecked = true
            et_age.setText(obj?.ageStr)
            sm_xue.addMenuItemForTitle(xueItemList, mx)
            level=""
        }
        et_jj.setText(obj?.content)
        et_phone.setText(obj?.seniority)//资格证


    }

    override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
        if (buttonView != null) {
            if (buttonView.id == cb_age.id) {
                cb_xue.isChecked = !isChecked
            } else if (buttonView.id == cb_xue.id) {
                cb_age.isChecked = !isChecked
            }
        }
    }


    override fun closeMvp() {
    }

}
